package com.lightsaber.trade.as.service.reta;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lightsaber.trade.as.dao.reta.OrderDao;
import com.lightsaber.trade.as.dao.reta.OrderItemDao;
import com.lightsaber.trade.as.dao.reta.ProductDao;
import com.lightsaber.trade.as.entity.reta.Order;
import com.lightsaber.trade.as.entity.reta.OrderItem;
import com.lightsaber.trade.as.entity.reta.Product;
import com.lightsaber.trade.core.dao.BaseDao;
import com.lightsaber.trade.core.service.BaseServiceImpl;

@Service
@Transactional
public class OrderItemManager extends BaseServiceImpl<OrderItem, String> {
    @Autowired
    private OrderItemDao OrderItemDao;
    @Autowired
    private OrderDao OrderDao;
    @Autowired
    private ProductDao productDao;

    @Override
    protected BaseDao<OrderItem, String> getDao() {
        return OrderItemDao;
    }

    public List<OrderItem> findPageByOrder(String OrderId) {

        Order Order = OrderDao.get(OrderId);

        return OrderItemDao.findByOrder(Order);
    }

    public void confirmSelectedProducts(String OrderId, Map<String, String> selectedIdsMap) {
        Order Order = OrderDao.get(OrderId);

        for (String id : selectedIdsMap.keySet()) {
            Product product = productDao.get(id);

            OrderItem OrderItem = new OrderItem();
            OrderItem.setProduct(product);
            OrderItem.setOrder(Order);
            OrderItem.setPrice(product.getDefaultPrice());
            OrderItem.setNumber(1f);

            this.save(OrderItem);
        }

    }

    public void delete(String[] ids) {
        for (String id : ids) {
            OrderItemDao.delete(id);
        }

    }

    public void saveNumber(List<OrderItem> results) {
        for (OrderItem OrderItem : results) {
            this.save(OrderItem);
        }

        getDao().getSession().flush();
        getDao().getSession().clear();
    }
}
